package com.iman.fetion.mina;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.TransportType;
import org.apache.mina.transport.socket.nio.SocketSessionConfig;

public class FetionServerHandler extends IoHandlerAdapter {

	public FetionMessage fm;
	public FetionMessage fmHttp;
	public String mobile = null;
	public String fetionId = null;
	public String password = null;
	public IoSession session;
	public String fetionUri;
	public String sipc_proxy;
	private StringBuffer buff = new StringBuffer();

	public void exceptionCaught(IoSession session, Throwable t)
			throws Exception {
		t.printStackTrace();
		session.close();
	}

	public void messageReceived(IoSession session, Object msg) throws Exception {
		this.session = session;
		String str = msg.toString();
		System.out.println("Reveiced:" + str);
		if (str.indexOf("&@OVER") == -1) {
			buff.append(str).append("\r\n");
		} else {
			str = str.replaceAll("&@OVER", "");
			buff.append(str);
			System.out.println("Sended:" + buff.toString());
			handMessage(session, buff.toString());
			buff = new StringBuffer();
		}

	}

	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("Session created...");

		if (session.getTransportType() == TransportType.SOCKET) {
			System.out.println("Session setBuffer Size...");
			((SocketSessionConfig) session.getConfig())
					.setReceiveBufferSize(1024 * 100);
			((SocketSessionConfig) session.getConfig())
					.setSendBufferSize(1024 * 100);
		}
		session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
	}

	public void sessionClosed(IoSession session) throws Exception {

		System.out.println("Session closed..." + session.toString());

	}

	public void writeFlex(String msg) {
		session.write(msg);
		System.out.println("SendedToFlex:" + msg);
	}

	public void handMessage(IoSession session, String message) {
		try {

			if (message != null) {
				message = message.trim();
				if (message.startsWith("<policy-file-request/>")) {
					String xml = "<cross-domain-policy>";
					xml += "<allow-access-from domain=\"*\" to-ports=\"*\" />";
					xml += "<allow-access-from domain=\"*\"/>";
					xml += "</cross-domain-policy>";
					writeFlex(xml + "\0");
					System.out.println("Response the policy file to client...");

				} else if (message.startsWith("<USERINFO>")) {
					String[] data = message.split("#");
					fm.sendUserInfoToServer(data[1], data[2], data[3], data[4]);

				} else if (message.startsWith("<USERQUIT/>")) {
					fm.closeSocket();
					fm = null;
				} else if (message.startsWith("<FetionUser>")) {
					if (fm != null) {
						return;
					}
					fm = new FetionMessage(this);
					String[] infos = message.split("#");
					mobile = infos[1].substring(2);
					fetionId = infos[2].substring(2);
					password = infos[3].substring(2);

					if (mobile != null) {
						fm.mobile = mobile;
					}
					if (fetionId != null) {
						fm.fetionId = fetionId;
					}
					if (password != null) {
						fm.password = password;
					}
					fm.getFetionUri();
					if (fm.fetionUri == null) {
						String error = "I_LOGIN_FAIL#000000000#I:32 "
								+ "#00000000#00000000";
						writeFlex(error);
						session.close();
						fm = null;
						return;
					}
					fm.getSipcProxy();
					fm.openSocket();
					fm.getNonce();
					fm.sendResponse();
					// fm.subPresence();
					ThreadPool.doIt(fm);

					// fm.getContactList();

					String data = null;
					if (fm.fetionUri != null) {
						data = "I_LOGIN_OK#" + fm.fetionId + "#I:31 " + "#"
								+ fm.fetionUri + "#" + fm.mobile;
						// send2WebService();
					} else {
						data = "I_LOGIN_FAIL#" + fm.fetionId + "#I:32 " + "#"
								+ fm.fetionUri + "#" + fm.mobile;
					}
					writeFlex(data);

					System.out.println("<FetionUser>=" + data);

					fm.getPersonalInfo();
					fm.getContactList();

				} else if (message
						.startsWith("<SENDMSG fetion.com.cn SIP-C/2.0>")) {
					String[] data = message.split("#MSG@");
					if (data[3] != null) {
						if (!"".equals(data[3])) {
							fm.sendMsg(data[3], data[2], data[1]);
						}
					}
					// var data:String = "<SENDMSG fetion.com.cn
					// SIP-C/2.0>#MSG@"+n+"#MSG@"+dstUri+"#MSG@"+message;
				} else if (message.startsWith("<GetPicCodeReg>")) {
					fmHttp = new FetionMessage();
					fmHttp.getPicCode();
					String data = "<GetPicCodeReg>" + "@#" + fmHttp.picId
							+ "@#" + fmHttp.picContent;
					System.out.println("<GetPicCodeReg>=" + data);
					writeFlex(data);
				} else if (message.startsWith("<GetPicCodePwd>")) {
					fmHttp = new FetionMessage();
					fmHttp.getPicCode();
					String data = "<GetPicCodePwd>" + "@#" + fmHttp.picId
							+ "@#" + fmHttp.picContent;
					System.out.println("<GetPicCodePwd>=" + data);
					writeFlex(data);
				} else if (message.startsWith("<GetSmsCode>")) {
					fmHttp = new FetionMessage();
					String[] data = message.split("#");
					fmHttp.tmpMobile = data[1];
					fmHttp.picCode = data[2];
					fmHttp.picId = data[3];
					fmHttp.getSmsCode();
					System.out.println("<GetSmsCode>=" + fmHttp.tmpMobile + " "
							+ fmHttp.picCode);
				} else if (message.startsWith("<UpdatePwd>")) {
					fmHttp = new FetionMessage();
					String[] data = message.split("#");
					fmHttp.tmpMobile = data[1];
					fmHttp.smsCode = data[2];
					fmHttp.newPassword = data[3];
					fmHttp.updatePwd();
					System.out.println("<UpdatePwd>=" + fmHttp.tmpMobile + " "
							+ fmHttp.smsCode + " " + fmHttp.newPassword);
				} else if (message.startsWith("<RegUser>")) {
					fmHttp = new FetionMessage();
					String[] data = message.split("#");
					fmHttp.tmpMobile = data[1];
					fmHttp.smsCode = data[2];
					fmHttp.newPassword = data[3];
					String feteionIdReg = fmHttp.regUser();

					System.out.println("<RegUser>=" + fmHttp.tmpMobile + " "
							+ fmHttp.smsCode + " " + fmHttp.newPassword);

					writeFlex("<RegUserResult>@#" + feteionIdReg);
				}// <KEEPALIVE/>
				else if (message.startsWith("<KEEPALIVE/>")) {

					fm.keepAlive();
				} else {
					fm.write(message);
					// fm.addMessage(message);

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
